package com.pctx.bibacrmrbac.controller;

import com.github.pagehelper.PageHelper;
import com.pctx.bibacommon.result.Result;
import com.pctx.bibacommon.util.DateTimeUtil;
import com.pctx.bibacrmrbac.pageHelper.PageInfo;
import com.pctx.bibacrmrbac.pojo.Role;
import com.pctx.bibacrmrbac.service.RoleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * Created by chason on 2018/2/24.16:26
 */

@RestController
@RequestMapping("role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @GetMapping("list4company")
    public Result getByCompanyUuid(@RequestParam String companyUuid) throws Exception {
        List<Role> list = roleService.getByCompanyUuid(companyUuid,null,null,null);
        return Result.success(list);
    }

    @GetMapping("list4companyPage")
    public Result getByCompanyUuidPage(@RequestParam String companyUuid,
                                       @RequestParam(value = "name",required = false) String name,
                                       @RequestParam(value = "startTime",required = false) String startTime,
                                       @RequestParam(value = "endTime",required = false) String endTime,
                                       @RequestParam(value = "page", defaultValue = "1") Integer page,
                                       @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) throws Exception {
        Date start = null;
        Date end = null;
        if (StringUtils.isNotEmpty(startTime))
            start = DateTimeUtil.toDate(startTime);
        if (StringUtils.isNotEmpty(endTime))
            end = DateTimeUtil.toDate(endTime);

        PageHelper.startPage(page, pageSize);
        List<Role> list = roleService.getByCompanyUuid(companyUuid, name, start, end);
        return Result.success(new PageInfo<Role>(list));
    }

    @GetMapping("detail")
    public Result detail(@RequestParam String uuid) throws Exception {
        Role role = roleService.getByUuid(uuid);
        return Result.success(role);
    }

    @PostMapping("add")
    public Result add(Role role) throws Exception {
        boolean flag = roleService.add(role);
        if (flag)
            return Result.success(null);
        else
            return Result.error(null);
    }

    @PostMapping("edit")
    public Result edit(Role role) throws Exception {
        boolean flag = roleService.update(role);
        if (flag)
            return Result.success(null);
        else
            return Result.error(null);
    }

    @GetMapping("del")
    public Result del(@RequestParam String uuid) throws Exception {
        boolean flag = roleService.delete(uuid);
        if (flag)
            return Result.success(null);
        else
            return Result.error(null);
    }
}
